/**
 * 主窗口通讯 【主进程】        *  主进程 ←→ 渲染进程 *
 */
import {app, ipcMain, BrowserWindow, dialog} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'
import {closeBrowserWindow, baiduPcSearch, baiduMobileSearch, douyinLiveListener} from './puppeteer/index'
import {dateFormat} from "../utils/util";

const fs = require('fs')
const json2xls = require('json2xls');

/** 接口数据 */

ipcMain.on('baiduSearch', (event, obj) => {
    //obj = { mode , keywords }
    var searchFun; //函数
    var modeTitle; //标题
    if (obj.mode === 1) {
        //手机搜索
        searchFun = baiduPcSearch;
        modeTitle = "电脑搜索";
    } else {
        //pc搜索
        searchFun = baiduMobileSearch;
        modeTitle = "手机搜索";
    }

    searchFun(obj.keywords).then((array) => {
        if (array && array.length) {
            console.log(modeTitle + '搜索成功了' + JSON.stringify(array))
            dialog.showSaveDialog({
                filters: [{name: '百度广告排名' + modeTitle, extensions: ['xls', 'xlsx']}],
                title: '文件另存为',
                defaultPath: '百度广告排名' + modeTitle + '-' + dateFormat('yyyy-MM-dd HH：mm', new Date()),
            }).then((res) => {
                console.log(res)
                fs.writeFileSync(res.filePath, json2xls(array), 'binary');
            }).catch((req) => {
                console.log(req)
            })
        }
        event.reply('baiduSearchSuccess', array)
    }).catch((err) => {
        dialog.showMessageBox({type: 'info', title: '提示消息', message: modeTitle + '发生错误!' + err})
    })
})

ipcMain.on('douyinLive', (event, obj) => {
    //obj = { gameType , link}
    douyinLiveListener(obj.link, event)
})


ipcMain.on('closeBrowserWindow', (event, obj) => {
    closeBrowserWindow()
})

/**
 * 创建窗口
 */
ipcMain.on('createWindow', (event, options) => {
    //{show,width,height,local,url,route}
    const win = new BrowserWindow({
        show: options.show == null ? true : options.show,
        width: options.width || 1000,
        height: options.height || 800,
        webPreferences: {nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION}
    })

    let url;
    if (options.online) {
        //在线页面
        url = options.url;
    } else {
        //本地页面
        var route = options.route ? '/#' + options.route : '';
        if (process.env.WEBPACK_DEV_SERVER_URL) {
            url = process.env.WEBPACK_DEV_SERVER_URL + route
            if (!process.env.IS_TEST) win.webContents.openDevTools()
        } else {
            createProtocol('app')
            url = 'app://./index.html' + route
        }
    }
    // console.log('打开地址：' + url)
    win.loadURL(url)
})
